package tool;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import exception.PathVariablePrefixNotLettersException;

/*
 * 在多个@Controller类之间共享的声明@ExceptionHandler，@InitBinder或@ModelAttribute方法的@Component类的特殊化
 * 带有注解的类@ControllerAdvice可以显式声明为Bean
 */
@ControllerAdvice
public class PathVariableRequestMappingHandlerControllerAdvice {
    /* @ExceptionHandler用于在特定处理器类或处理器方法中处理异常，使用此注解的处理器方法有多种签名 */
    @ExceptionHandler(value = { PathVariablePrefixNotLettersException.class })
    public ModelAndView handleException(Exception e) {
        ModelAndView modelAndView = new ModelAndView("exception");
        if (e instanceof PathVariablePrefixNotLettersException) {
            modelAndView.addObject("exception", e.getMessage());
        } else {
            e = new Exception("捕获了一个预料之外的错误");
            modelAndView.addObject("exception", e.getMessage());
        }
        return modelAndView;
    }
}
